import { Card, Col, Button, Cascader,Checkbox, DatePicker, Form, Input, Row, Select, Upload,message } from 'antd';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { cityArray } from './data/cityData'
import nationalitiesData from './data/nationalities'
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import {
  getusrBaseInfo,
  putusrBaseInfo,
}from '@/services/baseinfo'

const { RangePicker } = DatePicker;
const { TextArea } = Input;

const normFile = (e: any) => {
  if (Array.isArray(e)) {
    return e;
  }
  return e?.fileList;
};

const Projects: React.FC = () => {
  const [componentDisabled, setComponentDisabled] = useState<boolean>(true);//设置组件是否可填
  const [userInfo, setUserInfo] = useState(null); // 用于保存接口返回的用户基本信息
  // console.log(userInfo)
  const [form] = Form.useForm();
  // // 设置当前选择的省份和城市
  // const [selectedProvince, setSelectedProvince] = useState(null);
  // // 处理省份选择变化
  // const handleProvinceChange = (value) => {
  //   setSelectedProvince(value);
  //   // console.log(value);
  // };


  //检验身份证格式是否正确
  const validateID = (_, value) => {
    // 定义身份证号的正则表达式
    const idRegex = /^[1-9]\d{5}(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[1-2]\d|3[01])\d{3}[0-9Xx]$/;
    // 检查输入值是否符合正则表达式的模式
    if (!idRegex.test(value)) {
      return Promise.reject('请输入正确的身份证号');
    }
    return Promise.resolve();
  };
  const phoneRegex = /^1[3-9]\d{9}$/;//手机号码正则表达式
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;//邮箱正则表达式

  // 特长有标签样式
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 20 },
    },
  };
  // 特长无标签样式
  const formItemLayoutWithOutLabel = {
    wrapperCol: {
      xs: { span: 24, offset: 0 },
      sm: { span: 20, offset: 4 },
    },
  };

  // 定义表单的初始值，根据您的需求设置每个表单字段的初始值
  const initialValues = {
      gender: userInfo?.gender,
      ethnicity: userInfo?.ethnicity,
      hometown: (userInfo?.hometown||"").split(','),
      birth: moment(`${userInfo?.birth}`),
      politicalParty: userInfo?.politicalParty,
      idCard: "421127199912295313",
      originPlace: (userInfo?.originPlace||"").split(','),
      phoneNumber: userInfo?.phoneNumber,
      email: `${userInfo?.email}`,
      collegeEntranceScore: userInfo?.collegeEntranceScore,
      isReported: userInfo?.isReported,
      hobbies: userInfo?.hobbies,
  };
  const advantages = ['唱歌', '跳舞', 'RAP', '篮球'];
  useEffect(() => {
    // 在组件加载时调用接口函数
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      // 调用接口函数并传递必要的参数
      const response = await getusrBaseInfo(null,null );

      // 处理返回的数据
      if (response && response.result) {
        setUserInfo(response.result); // 将接口返回的数据保存到状态中
      }
    } catch (error) {
      console.error('Error fetching user info:', error);
    }
  };
  // 表单重置函数
  const handleFormReset = () => {
    form.resetFields(); // 使用ant-design表单的resetFields方法将表单字段恢复为初始值
  };
  if (userInfo === null || userInfo === undefined) {
    return <p>Loading...</p>;
  }
  return (
    <Card>
      <Checkbox
        checked={componentDisabled}
        onChange={(e) => setComponentDisabled(e.target.checked)}
      >
        信息有错?点击更改!
      </Checkbox>
      <Form
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 10 }}
        layout="horizontal"
        disabled={componentDisabled}
        initialValues={initialValues} // 设置表单的初始值
        form={form}
      >
        <Row gutter={16}>
          <Col span={12}>
            {/* 性别 */}
            <Form.Item
              label="性别"
              name="gender"
            >
              <Select allowClear disabled>
                <Select.Option value="0">男</Select.Option>
                <Select.Option value="1">女</Select.Option>
              </Select>
            </Form.Item>
            {/* 民族 */}
            <Form.Item
              label="民族"
              name="ethnicity"
            >
              <Select allowClear disabled>
                {nationalitiesData.map((nationality, index) => (
                  <Select.Option key={index} value={nationality}>
                    {nationality}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            {/* 籍贯 */}
            <Form.Item
              label="籍贯"
              name="hometown"
            >
              <Cascader
                options={cityArray}
                disabled
                placeholder="请选择省份"
              />
            </Form.Item>
            {/* 出生年月 */}
            <Form.Item
              label="出生年月"
              name="birth"
            >
              <DatePicker disabled />
            </Form.Item>
            {/* 政治面貌 */}
            <Form.Item
              label="政治面貌"
              name="politicalParty"
            >
              <Select allowClear disabled>
                <Select.Option value="0">中共党员</Select.Option>
                <Select.Option value="1">中共预备党员</Select.Option>
                <Select.Option value="2">共青团员</Select.Option>
                <Select.Option value="3">群众</Select.Option>
                <Select.Option value="4">民主党派</Select.Option>
                <Select.Option value="5">无党派人士</Select.Option>
              </Select>
            </Form.Item>
            {/* 身份证号 */}
            <Form.Item
              label="身份证号"
              name="idCard"
            >
              <Input disabled></Input>
            </Form.Item>
            {/* 生源地 */}
            <Form.Item
              label="生源地"
              name="originPlace"
            >
              <Cascader
                options={cityArray}
                disabled
                placeholder="请选择省份"
              />
            </Form.Item>
            {/* 高考分数 */}
            <Form.Item
              label="高考分数"
              name="collegeEntranceScore"
            >
              <Input disabled/>
            </Form.Item>
            {/* 手机号码 */}
            <Form.Item
              label="手机号码"
              name="phoneNumber"
              rules={[
                {
                  required: true,
                },
                {
                  pattern: phoneRegex,
                  message: '请输入有效的手机号码',
                },
              ]}
            >
              <Input></Input>
            </Form.Item>
            {/* 邮箱地址 */}
            <Form.Item
              label="邮箱地址"
              name="email"
              rules={[
                {
                  required: true,
                  message: '请输入邮箱地址',
                },
                {
                  pattern: emailRegex,
                  message: '请输入有效的邮箱地址',
                },
              ]}
            >
              <Input />
            </Form.Item>

            {/* 是否确认报到 */}
            <Form.Item
              label="是否确认报到"
              name="isReported"
              rules={[
                {
                  required: true,
                  message: '请选择内容',
                },
              ]}
            >
              <Select >
                <Option value="1">是</Option>
                <Option value="0">否</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="爱好"
              name="hobbies"
            >
              <TextArea rows={4} />
            </Form.Item>
            <Form.List name="advantages" initialValue={advantages}>
              {(fields, { add, remove }, { errors }) => (
                <>
                  {fields.map((field, index) => (
                    <Form.Item
                      {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                      label={index === 0 ? '特长（获得奖项等）' : ''}
                      required={false}
                      key={field.key}
                    >
                      <Form.Item
                        {...field}
                        validateTrigger={['onChange', 'onBlur']}
                        noStyle
                      >
                        <Input style={{ width: '60%' }} />
                      </Form.Item>
                      {fields.length > 1 ? (
                        <MinusCircleOutlined
                          className="dynamic-delete-button"
                          onClick={() => remove(field.name)}
                        />
                      ) : null}
                    </Form.Item>
                  ))}
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => add()}
                      style={{ width: '60%', marginLeft: 300 }}
                      icon={<PlusOutlined />}
                    >
                      添加特长
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
            <Form.Item >
              {/* 重置按钮 */}
              <Button type="primary" onClick={handleFormReset} style={{ height: 40, width: '100%', marginLeft: 180, marginTop: 50 }}>放弃修改</Button>
              {/* 提交按钮 */}
              <Button
                type="primary"
                style={{ height: 40, width: '100%', marginLeft: 180, marginTop: 50 }}
                onClick={() => {
                  // 获取表单的值
                  form.validateFields().then((values) => {
                    if (values.birth) {
                      values.birth = values.birth.format('YYYY-MM-DD');
                    }
                    if(values.hometown){
                      values.hometown = values.hometown.join(',');
                    }
                    if(values.advantages){
                      values.advantages = values.advantages.join(',');
                    }
                    if(values.originPlace){
                      values.originPlace = values.originPlace.join(',');
                    }
                    console.log('表单提交的值：', values);
                    values.stuName = localStorage.getItem('userName')
                    values.stuCode = localStorage.getItem('userAccount')
                    putusrBaseInfo(null, values)
                    .then((response) => {
                      console.log('API response:', response);
                      if( response.code == 200){
                        message.success("提交成功")
                        window.location.reload();
                      }
                    })
                    .catch((error) => {
                      console.error('API error:', error);
                    });
                  });
                }}
              >
                提交更改
              </Button>

            </Form.Item>
          </Col>
        </Row>
      </Form >
    </Card >
  );
};

export default Projects;
